#include "myRTC.h"
#include <stdio.h>
#include "platformAPI.h"

#define tskRTC_PRIORITY (tskIDLE_PRIORITY + 20)

static time_t s_timeinfo;

static xTaskHandle rtcTsk;


/* notice that application updates the GMT from the server every minute.*/
void sw_rtc_tick_handler(uint32_t id)
{
    s_timeinfo += id;
}


extern int RtlMsleepOS(uint32_t ms);
static void rtcThread(void *parameter)
{
    while(1)
    {
        sw_rtc_tick_handler(1);
        RtlMsleepOS(1000);
    }
}

int myRTCstart(void)
{
    if(xTaskCreate(rtcThread, 
		   ((const char*)"rtcThread"), 
		   50, 
		   NULL,
		   tskRTC_PRIORITY,
		   &rtcTsk) != pdPASS)
    {	
        printf("create rtc task failed\n");
        return -1;
    }
    return 0;
}


int myRTCstop(void)
{
    vTaskDelete(rtcTsk);
    return 0;
}

static int parseTimeMessage(uint8_t *date, struct tm *result)
{
    /*date should be like: "2016-03029T06:56:08.514Z"*/
    uint8_t s_year[5] = {0};
    uint8_t s_mon[3] = {0};
    uint8_t s_day[3] = {0};
    uint8_t s_hour[3] = {0};
    uint8_t s_minute[3] = {0};
    uint8_t s_second[3] = {0};
    
    uint8_t count = 0;
    
    if(*(date + 4)  == '-' &&
       *(date + 7)  == '-' &&
       *(date + 10) == 'T' &&
       *(date + 13) == ':' &&
       *(date + 16) == ':' &&
       *(date + 19) == '.' &&
       *(date + 23) == 'Z')  
    {
        /*right date format*/
        memcpy(s_year,date,4);
        memcpy(s_mon,date+5,2);
        memcpy(s_day,date+8,2);
        memcpy(s_hour,date+11,2);
        memcpy(s_minute,date+14,2);
        memcpy(s_second,date+17,2);
        
        result->tm_year = atoi(s_year);
        result->tm_mon  = atoi(s_mon);
        result->tm_mday = atoi(s_day);
        result->tm_hour = atoi(s_hour);
        result->tm_min  = atoi(s_minute);
        result->tm_sec  = atoi(s_second);
        
        return 0;
    }
    return -1;
}


int8_t updateDateFromServer(uint8_t *pGMTmessage)
{
    struct tm tmp;
    time_t seconds;
    struct tm *p_time;
 
    
    int32_t ret = -1;
    struct tm timeinfo;

    ret = parseTimeMessage(pGMTmessage, &tmp);
    if(ret == 0)
    {
        tmp.tm_year -= 1970;
        tmp.tm_hour += 1;
        seconds = mktime(&tmp);
        s_timeinfo = seconds;
    }
    return ret;
}


time_t myRTCread(void)
{
    return s_timeinfo;
}



